// content.js 

function isGooglePlayOrDiandianUrl(url) {
    if (url == null) {
        return false;
    }
    if (url.indexOf("play.google.com/store/apps/details?id=") >= 0) {
        return true;
    }
    if (url.indexOf("app.diandian.com") >= 0 && url.indexOf("googleplay") >= 0 && url.indexOf("id=") >= 0) {
        return true;
    }
    return false;
}

function addListener() {
    chrome.runtime.onMessage.addListener(
        async function(request, sender, sendResponse) {
            var data = request.data
            sendResponse("content receive success")

            var respText = JSON.stringify(data, null, 4)
            if (data.hasOwnProperty("status")) {
                alert(respText)
            } else {
                var result = confirm("确定要复制以下内容 : \n" + respText)
                if (result) {
                    try {
                        await navigator.clipboard.writeText(respText);
                    } catch(e) {
                        alert("复制失败 : " + e)
                    }
                }
            }
        }
    );
}

function getQueryParams(url, key) {
    map = {};
    try {
        var params = url.split("?")[1];
        var keyvalue = params.split("&");
        for (var index = 0; index < keyvalue.length; index++) {
            var tmp = keyvalue[index].split("=");
            try{
                map[tmp[0]] = tmp[1];
            }catch(e){
            }
        }
    } catch(e){
        console.log("e : " + e);
    }
    return map[key];
}

function getPackageName(url) {
	return getQueryParams(url, "id")
}

function showCountryDialog() {
    const companyName = prompt("输入公司名称")
    // console.log("公司名称 : " + companyName)
    if (companyName == null) {
        // console.log("用户取消操作")
        return
    }
    addProductMonitor(companyName)
}

function addProductMonitor(company) {
    $('#update_select_app').css('display', "none")
    var appUrl = "http://www.hauyu.xyz/monitor/add_package/" + getPackageName(window.location.href) + "/"
    var curUrl = window.location.href
    if (curUrl.indexOf("app.diandian.com") >= 0 && curUrl.indexOf("googleplay?") >= 0 && curUrl.indexOf("id=") >= 0) {
        appUrl = appUrl + "?dd_url=" + encodeURIComponent(curUrl) + "&company=" + encodeURIComponent(company)
    } else {
        appUrl = appUrl + "?company=" + encodeURIComponent(company)
    }
    console.log(`app url : ${appUrl}`)
    chrome.runtime.sendMessage({url:appUrl}, function(response) {
        console.log("content : " + JSON.stringify(response))
        $('#update_select_app').css('display', "block")
        alert(JSON.stringify(response))
    });
}

function addMonitorButton() {
    $('body').append($("<div id='update_select_app' class='float_button'>添加监控</div>"))
    $('#update_select_app').css("word-break",  "break-all")
    $('#update_select_app').css("color",  "#fff")
    $('#update_select_app').css("width",  "6em")
    $('#update_select_app').css("height",  "6em")
    $('#update_select_app').css("position",  "fixed")
    $('#update_select_app').css("text-align",  "center")
    $('#update_select_app').css("line-height",  "5.4em")
    $('#update_select_app').css("top",  "4em")
    $('#update_select_app').css("right",  "4em")
    $('#update_select_app').css("border-radius",  "4em")
    $('#update_select_app').css("background-size",  "100% 100%")
    $('#update_select_app').css("cursor",  "pointer")
    $('#update_select_app').css("z-index",  "10000")
    $('#update_select_app').css("border",  "6px solid #1c86d1")
    $('#update_select_app').css("border-color",  "rgb(219, 229, 255)")
    $('#update_select_app').css("background",  "url('https://google-play.cdn.diandian.com/LUCM_Uj6hDLeHApqsPhM7l6SCuj25OEdCkpfaWT7rRoizEo-Kr3A0tggA_ejwZDkmYY')")
    $('#update_select_app').click(function() {
        if (isGooglePlayOrDiandianUrl(window.location.href)) {
            showCountryDialog()
        } else {
            alert("url 内容不匹配")
        }
    })
}

function addMonitorInternal() {
    // console.log("google play monitor document is ready")
    var execTimes = 0
    var monitorTimer = setInterval(function(){
        execTimes++
        // console.log('google play monitor date : ' + new Date() + " , times : " + execTimes)
        if (execTimes >= 5) {
            clearInterval(monitorTimer)
        } else {
            if (isGooglePlayOrDiandianUrl(window.location.href)) {
                // console.log('google play monitor cancel date : ' + new Date())
                clearInterval(monitorTimer)
                addListener();
                addMonitorButton();
            }
        }
    }, 1000)
}

window.onload = function(){
    addMonitorInternal()
}

